package single_ws

import (
	"encoding/json"
	"fmt"
	"hft/tools/ws/single_ws/e"
	"hft/tools/ws/single_ws/model"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

func Start() {
	go model.Heartbeat()           //心跳检测
	go model.Manager.MessageChan() //消息管道
}

func WsHandler(c *gin.Context) {
	uid := c.Query("uid")     // 自己的id
	toUid := c.Query("toUid") // 对方的id
	page := c.Query("page")   //页面名称
	conn, err := (&websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}).Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err)
		http.NotFound(c.Writer, c.Request)
		return
	}
	res := model.IsClientExist(model.Manager.Clients, model.CreateId(page, uid, toUid))
	if res {
		var replyMsg = &model.ReplyMsg{Code: e.WebsocketHasExist, Content: "聊天已存在"}
		data, _ := json.Marshal(&replyMsg)
		conn.WriteMessage(websocket.TextMessage, data)
		conn.Close()
		return
	}
	client := &model.Client{
		ID:        model.CreateId(page, uid, toUid),
		SendID:    model.CreateId(page, toUid, uid),
		Socket:    conn,
		Send:      make(chan []byte),
		HeartTime: time.Now().Unix(),
		Page:      page,
	}

	model.Manager.Register <- client
	go func() {
		defer func() {
			if r := recover(); r != nil {
				log.Printf("link read panic: %+v\n", r)
			}
		}()
		client.Read()
	}()
	go func() {
		defer func() {
			if r := recover(); r != nil {
				log.Printf("link read panic: %+v\n", r)
			}
		}()
		client.Write()
	}()
}
